package com.tiniplanet.webgate.service.impl;

import java.util.ArrayList;
import java.util.Collection;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;

import com.tiniplanet.webgate.dao.BaseDao;
import com.tiniplanet.webgate.dao.CredentialDao;
import com.tiniplanet.webgate.entity.Credential;
import com.tiniplanet.webgate.entity.Role;
import com.tiniplanet.webgate.service.CredentialService;

public class CredentialServiceImpl extends BaseServiceImpl<Credential, Long>
		implements CredentialService {

	@Autowired
	private CredentialDao credentailDao;

	public CredentialServiceImpl(BaseDao<Credential, Long> baseDao) {
		super(baseDao);
		// TODO Auto-generated constructor stub
	}

	@Override
	public User getSecurityInstance(Credential credential) {
		String username = credential.getUsername();
		String password = credential.getPassword();
		boolean enabled = true;
		boolean accountNonExpired = true;
		boolean credentialsNonExpired = true;
		boolean accountNonLocked = true;

		Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
		final Role role = credential.getRole();
		GrantedAuthority authority = new GrantedAuthority() {
			private static final long serialVersionUID = 1699155761177840128L;

			@Override
			public String getAuthority() {
				return role.getRoleName();
			}
		};
		authorities.add(authority);
		User user = new User(username, password, enabled, accountNonExpired,
				credentialsNonExpired, accountNonLocked, authorities);
		return user;
	}

	@Override
	public Credential getByUsername(String username) {
		return credentailDao.getByUsername(username);
	}

}
